package com.algorithm.leetcode.addtwonums;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ADMIN
 * @date 2021/7/27 23:41
 */
public class AddTwoNums {
    public static void main(String[] args) {
        String s = Integer.toString(809435);
        List<Character> objects = new ArrayList<>();
        for (int i1 = s.length() - 1; i1 >= 0; i1--) {
            char c = s.charAt(i1);
            objects.add(c);
        }
        System.out.println(Arrays.toString(objects.toArray()));
        ListNode listNode3 = new ListNode(9);
        ListNode listNode2 = new ListNode(4, listNode3);
        ListNode listNode1 = new ListNode(2, listNode2);
        ListNode listNode4 = new ListNode(9);

        ListNode listNode5 = new ListNode(4, listNode4);
        ListNode listNode7 = new ListNode(6, listNode5);
        ListNode listNode6 = new ListNode(5, listNode7);
        System.out.println(get(listNode1, listNode6));
    }
    public static ListNode get(ListNode l1, ListNode l2) {
        StringBuilder str1 = new StringBuilder("" + l1.val);
        StringBuilder str2 = new StringBuilder("" + l2.val);
        if (l1.val == 0 && l1.next == null) {
            return l2;
        }
        if (l2.val == 0 && l2.next == null) {
            return l1;
        }
        while (l1.next != null) {
            str1.append(l1.next.val);
            l1 = l1.next;

        }
        str1.reverse();
        while (l2.next != null) {
            str2.append(l2.next.val);
            l2 = l2.next;
        }
        str2.reverse();
        String s = new BigDecimal(String.valueOf(str1)).add(new BigDecimal(String.valueOf(str2))).toString();
        ListNode listNode = new ListNode(Integer.parseInt(s.charAt(0) + ""));
        for (int length = 1; length < s.length(); length++) {
            listNode = new ListNode(Integer.parseInt(s.charAt(length) + ""), listNode);
        }
        return listNode;
    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(-1), pre = dummyHead;
        int t = 0;
        while (l1 != null || l2 != null || t != 0) {
            if (l1 != null) {
                t += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                t += l2.val;
                l2 = l2.next;
            }
            pre.next = new ListNode(t % 10);
            pre = pre.next;
            t /= 10;
        }
        return dummyHead.next;
    }
}

